<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理</title>
    <link rel="icon" th:href="@{/favicon.png}" type="image/png"/>
    <script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <link rel="stylesheet" th:href="@{/css/UserProfile.css}">
</head>
<body>
<div id="app">
    <!-- 返回主页面按钮 -->
    <button class="back-button" @click="goToMainPage">← 返回主页面</button>

    <div class="container">
        <!-- 左侧用户信息展示 -->
        <div class="user-panel">
            <div class="avatar-container">
                <img :src="user.avatar" alt="用户头像" class="avatar">
            </div>
            <div class="username">{{ user.username }}</div>

            <!-- 模式选择器 -->
            <div class="mode-selector">
                <div
                        class="mode-btn"
                        :class="{ active: activeMode === 'avatar' }"
                        @click="activeMode = 'avatar'"
                >
                    头像管理
                </div>
                <div
                        class="mode-btn"
                        :class="{ active: activeMode === 'info' }"
                        @click="activeMode = 'info'"
                >
                    信息管理
                </div>
            </div>
        </div>

        <!-- 右侧表单区域 -->
        <div class="form-panel">
            <!-- 头像管理表单 -->
            <div v-if="activeMode === 'avatar'">
                <h2 class="form-title">头像管理</h2>
                <div class="avatar-form">
                    <div class="avatar-preview">
                        <img :src="avatarPreview || user.avatar" alt="头像预览">
                    </div>

                    <input
                            type="file"
                            id="avatarFile"
                            class="file-input"
                            accept="image/*"
                            @change="handleAvatarChange"
                    >
                    <label for="avatarFile" class="file-label">选择图片</label>

                    <button class="submit-btn" @click="uploadAvatar">确认上传</button>
                </div>
            </div>

            <!-- 信息管理表单 -->
            <div v-if="activeMode === 'info'">
                <h2 class="form-title">账户信息管理</h2>
                <form class="info-form" @submit.prevent="updateUserInfo">
                    <div class="form-group">
                        <label class="form-label">用户名</label>
                        <input
                                type="text"
                                class="form-input"
                                v-model="userInfo.username"
                                required
                        >
                    </div>

                    <div class="form-group">
                        <label class="form-label">新密码</label>
                        <input
                                type="password"
                                class="form-input"
                                v-model="userInfo.newPassword"
                                placeholder="留空则不修改"
                        >
                    </div>

                    <div class="form-group">
                        <label class="form-label">确认新密码</label>
                        <input
                                type="password"
                                class="form-input"
                                v-model="userInfo.confirmPassword"
                        >
                    </div>

                    <button type="submit" class="submit-btn">保存更改</button>
                </form>
            </div>
        </div>
    </div>

    <!-- 底部版权声明 -->
    <div class="footer">
        Copyright &copy; 2025 Wooming Games. 版权所有。
    </div>
</div>
<script>
    const { createApp, ref, reactive, watch } = Vue;

    createApp({
        setup() {
            // 用户数据
            const user = reactive({
                username: localStorage.getItem('username'),
                avatar: "" // 默认头像
            });

            // 当前激活的模式 (avatar/info)
            const activeMode = ref('avatar');

            // 头像管理相关数据
            const avatarFile = ref(null);
            const avatarPreview = ref(null);

            // 用户信息表单数据
            const userInfo = reactive({
                username: user.username,
                newPassword: '',
                confirmPassword: ''
            });

            // 监听用户名变化并更新表单
            watch(() => user.username, (newVal) => {
                userInfo.username = newVal;
            });

            // 处理头像选择
            const handleAvatarChange = (event) => {
                const file = event.target.files[0];
                if (file) {
                    avatarFile.value = file;

                    // 创建预览
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        avatarPreview.value = e.target.result;
                    };
                    reader.readAsDataURL(file);
                }
            };

            // 上传头像
            const uploadAvatar = async () => {
                if (!avatarFile.value) {
                    alert('请先选择图片');
                    return;
                }

                try {
                    // 创建FormData对象
                    const formData = new FormData();
                    formData.append('file', avatarFile.value);

                    // 发送请求到后端 (实际URL需替换)
                    const response = await axios.post('/api/upload', formData, {
                        headers: {
                            'Content-Type': 'multipart/form-data',
                            'Authorization': 'Bearer ' + localStorage.getItem('jwt')
                        }
                    });

                    // 更新用户头像
                    axios.get('/api/headshot',{
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': 'Bearer ' + localStorage.getItem('jwt')
                        },
                        responseType: 'blob'
                    }).then((r) => {
                        user.avatar = URL.createObjectURL(r.data)
                    })
                    avatarPreview.value = null;
                    avatarFile.value = null;

                    alert('头像更新成功！');
                } catch (error) {
                    console.error('头像上传失败:', error);
                    alert('头像更新失败，请重试');
                }
            };

            // 更新用户信息
            const updateUserInfo = async () => {
                // 检查密码一致性
                if (userInfo.newPassword && userInfo.newPassword !== userInfo.confirmPassword) {
                    alert('两次输入的密码不一致');
                    return;
                }

                try {
                    // 准备请求数据
                    const data = {
                        username: userInfo.username,
                        password: userInfo.newPassword
                    };

                    // 发送请求到后端 (实际URL需替换)
                    const response = await axios.post('/api/user/change', data, {
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': 'Bearer ' + localStorage.getItem('jwt')
                        }
                    });

                    // 更新本地用户数据
                    user.username = userInfo.username;
                    localStorage.setItem('username', userInfo.username);

                    // 保存新的JWT
                    if (response.data.code === 200) {
                        localStorage.setItem('jwt', response.data.data);
                    }

                    // 清空密码字段
                    userInfo.newPassword = '';
                    userInfo.confirmPassword = '';

                    alert('用户信息更新成功！');
                } catch (error) {
                    console.error('用户信息更新失败:', error);
                    alert('更新失败，请重试');
                }
            };

            // 返回主页面
            const goToMainPage = () => {
                // 实际项目中应使用路由跳转
                console.log('返回游戏主页面');
                window.location.href = '/';
            };

            return {
                user,
                activeMode,
                avatarPreview,
                userInfo,
                handleAvatarChange,
                uploadAvatar,
                updateUserInfo,
                goToMainPage
            };
        },
        created () {
            this.getInitials()
        },
        methods: {
            getInitials() {
                axios.get('/api/headshot',{
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': 'Bearer ' + localStorage.getItem('jwt')
                    },
                    responseType: 'blob'
                }).then((r) => {
                    this.user.avatar = URL.createObjectURL(r.data)
                })
            }
        }
    }).mount('#app');
</script>
</body>
</html>